<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手写promise</title>
</head>

<body>
    <script>
        function Promise(excutor) {
            var self = this
            self.onResolvedCallback = []
            function resolve(value) {
                setTimeout(() => {
                    self.data = value
                    self.onResolvedCallback.forEach(callback => {
                        callback(value);
                    });
                })
            }
            excutor(resolve.bind(self))//将resolve作为实参传入excutor(resolve, reject)
        }
        Promise.prototype.then = function (onResolved) {
            var self = this
            return new Promise(resolve => {
                self.onResolvedCallback.push(function () {
                    var result = onResolved(self.data)//执行then函数传入的函数参数
                    if (result instanceof Promise) {
                        result.then(resolve)
                    } else {
                        resolve(result)
                    }
                })
            })
        }
        var p2 = new Promise(
            function (resolve, reject) {//excutor,在Promise的构造函数return前执行
                resolve(1);//此处的resolve是Promise内传过来的函数
            }
        );
        p2.then(//then方法内封装了一个Promise
            res => {//传入self.data
                console.log(res); // 1
                return res + 1;//返回的值如果是Promise类型则将此Promise.then()插入到调用链上,

            },
            err => {
                return res + 100;
            }
        ).then(
            res => {
                console.log(res + ' 2');
                return res + 100;
            }, err => {
                return res + 100;
            });
    </script>
</body>

</html>